/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkUtil/MkMemQueue.h"
#include "MkUtil/MkThread.h"
#include <gtest/gtest.h>

TEST(WaitEvent, waitTest)
{
    void *WaitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    WaitForSingleObject(WaitEvent, 100);
    CloseHandle(WaitEvent);
}

TEST(MkMemQueue, MemQueueNoWait)
{
    CMkMemQueue *pQueue = CMkMemQueue::CreateNew(18);
    Int8 pIn[Len16] = { 0 };
    Int8 pOut[Len16] = { 0 };
    Uint32 ErrorCode = NoneError;
    Uint32 OutLen = Len16;

    strcpy(pIn, "123");
    ErrorCode = pQueue->Input((Uint8*)pIn, Len16);
    EXPECT_EQ(NoneError, ErrorCode);
    ErrorCode = pQueue->OutPut((Uint8*)pOut, &OutLen);
    EXPECT_EQ(NoneError, ErrorCode);
    EXPECT_STREQ(pOut, pIn);

    ErrorCode = pQueue->Input((Uint8*)pIn, Len16);
    EXPECT_EQ(NoneError, ErrorCode);

    //input failed
    ErrorCode = pQueue->Input((Uint8*)pIn, Len16,1);
    EXPECT_NE(NoneError, ErrorCode);

    OutLen = 10;
    ErrorCode = pQueue->OutPut((Uint8*)pOut, &OutLen, FALSE);
    EXPECT_EQ(NoneError, ErrorCode);
    EXPECT_EQ(10, OutLen);

    ErrorCode = pQueue->OutPut((Uint8*)pOut, &OutLen, FALSE);
    EXPECT_EQ(NoneError, ErrorCode);
    EXPECT_EQ(6, OutLen);

    ErrorCode = pQueue->OutPut((Uint8*)pOut, &OutLen);
    EXPECT_EQ(QueueEmpty, ErrorCode);

    pQueue->Realse();
    MkDelete(pQueue);
}

TEST(MkMemQueue, MemQueueWait)
{
    CMkThread InThread;
    CMkThread OutThread;
    Uint32 ErrorCode = NoneError;
    CMkMemQueue *pQueue = CMkMemQueue::CreateNew(20);
    Uint8 pbuf[16] = { 0 };
    if (pQueue) {
        pQueue->Input(pbuf, 16, 0xFFFFFF);
    }
    pbuf[0] = 100;
    pQueue->Input(pbuf, 2, 0);
    Uint32 OutLen = 2;
    while (1) {
        pQueue->OutPut(pbuf, &OutLen, 1, 0xFFFFFF);
        if (pbuf[0] == 100) {
            break;
        }
    }
    MkDelete(pQueue);
}